package org.csu.mybigpro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.csu.mybigpro.domain.User;
import org.csu.mybigpro.domain.UserRole;
import org.csu.mybigpro.persistence.UserMapper;
import org.csu.mybigpro.persistence.UserRoleMapper;
import org.csu.mybigpro.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeacherServiceImpl implements TeacherService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public List<User> getAllTeachers() {
        return userMapper.selectAllTeachers();
    }

    @Override
    public User getTeacherById(Long id) {
        // 先确认该用户是否是教师
        QueryWrapper<UserRole> query = new QueryWrapper<>();
        query.eq("user_id", id).eq("role_id", 3);
        Long count = userRoleMapper.selectCount(query);
        if (count == null || count == 0) return null;

        return userMapper.selectById(id);
    }

    @Override
    public List<User> getTeacherByName(String name) {
        return userMapper.selectTeachersByName(name);
    }

    @Override
    @Transactional
    public boolean addTeacher(User user) {
        int insert = userMapper.insert(user);
        if (insert > 0) {
            // 插入 user_role
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(3L);
            userRoleMapper.insert(userRole);
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean updateTeacher(User user) {
        // 确认是教师
        QueryWrapper<UserRole> query = new QueryWrapper<>();
        query.eq("user_id", user.getId()).eq("role_id", 3);
        Long count = userRoleMapper.selectCount(query);
        if (count == null || count == 0) return false;

        int update = userMapper.updateById(user);
        return update > 0;
    }

    @Override
    @Transactional
    public boolean deleteTeacher(Long id) {
        // 确认是教师
        QueryWrapper<UserRole> query = new QueryWrapper<>();
        query.eq("user_id", id).eq("role_id", 3);
        Long count = userRoleMapper.selectCount(query);
        if (count == null || count == 0) return false;

        // 删除关联的 user_role 记录
        int deletedUserRoles = userRoleMapper.delete(query);

        userRoleMapper.delete(query);
        int delete = userMapper.deleteById(id);
        // 两者都删除成功才算成功
        return deletedUserRoles > 0 && delete > 0;
    }
}
